package common.intercepter.service;

import cn.hutool.core.util.StrUtil;
import common.beans.User;
import common.config.AppConfig;
import common.util.AuthCode;
import common.util.CacheUtil;
import common.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class YuntsgAuthorizingService {

    @Resource
    CacheUtil cacheUtil;

    @Resource
    TokenAuthorizingService authService;


    public boolean decryptCookie(Cookie[] cookies) throws Exception {
//        log.info("开始解析yuntsg.com的cookie+++++++++++++++");
        Cookie userInfoCookie = filterUserInfoCookie(cookies);
        if (userInfoCookie == null) {
            return false;
        }
        String cookiestr = AuthCode.authcodeDecode(userInfoCookie.getValue(), AppConfig.COOKIE_KEY);
        if (cookiestr != null && cookiestr.contains("uid")) {
            Map<String, Object> decryptResultMap = new HashMap<String, Object>();
            String[] cookiearray = cookiestr.split(";");
            for (int x = 0; x < cookiearray.length; x++) {
                String[] newcookiearray = cookiearray[x].split(":");
                if (newcookiearray.length == 2) {
                    decryptResultMap.put(newcookiearray[0], newcookiearray[1]);
                }
            }
            /**true代表通过验证*/
            boolean notExpire = checkUserEndDate(decryptResultMap) && checkUnitEndDate(decryptResultMap) && checkLoginDate(decryptResultMap);
            if (!notExpire) {
                authService.expireCookie("userinfo");
                return false;
            }
            String uid = (String) decryptResultMap.get("uid");
            if (StrUtil.isEmpty(uid)) {
                authService.expireCookie("userinfo");
                return false;
            }
            UserUtil.setAccessId(uid);
            if (cacheUtil.existsKey("user")) {
                return true;
            }
            User user = new User();
            user.setUid(Integer.parseInt(uid));
            user.setGid(Integer.parseInt(decryptResultMap.get("gid").toString()));
            user.setRealname(URLDecoder.decode(decryptResultMap.get("realname").toString()));
            user.setUnitName(URLDecoder.decode(decryptResultMap.get("unitname").toString()));
            //2021年3月17日09:03:39 添加新管理员
            Object permission = decryptResultMap.get("permission");
            if (permission.equals("true") || permission.equals(true)) {
                System.out.println("添加isAdm" + UserUtil.getAccessId());
                user.setIsAdm(1);
            }
            //结束
            cacheUtil.saveObject("user", user);
            return true;
        }
        return false;
    }


    //获取名为userinfo的tsgyun.com的相应cookie
    private Cookie filterUserInfoCookie(Cookie[] cookies) {
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                String cookieName = cookie.getName();
                if (cookieName.equals("userinfo")) {
//                    System.out.println("userinfo存在" + cookie.getValue());
                    return cookie;
                }
            }
        }
        return null;
    }


    /**
     * 检查用户的过期时间设置
     */
    private boolean checkUserEndDate(Map<String, Object> m) {
        if (!m.containsKey("enddate") || m.get("enddate") == null) {
            return false;
        }
        boolean notExpire = Long.parseLong((String) m.get("enddate")) == 0 || Long.parseLong((String) m.get("enddate")) >= System.currentTimeMillis();
        return notExpire;
    }

    /**
     * 检查单位过期时间
     */
    private boolean checkUnitEndDate(Map<String, Object> m) {
        if (!m.containsKey("unitenddate") || m.get("unitenddate") == null) {
            return false;
        }
        boolean notExpire = Long.parseLong((String) m.get("unitenddate")) == 0 || Long.parseLong((String) m.get("unitenddate")) >= System.currentTimeMillis();
        return notExpire;
    }

    /**
     * 单位ip范围内30天必须登陆一次
     * 分项目没用；如果单位开启ip30天  那么lastinipdate=0的一定到不了这里会在登录时被拦截
     * 如果没开启 那么过来的lastinipdate  一定等于0
     */
    private boolean checkLastIpDate(Map<String, Object> m) {
        if (!m.containsKey("lastinipdate") || m.get("lastinipdate") == null) {
            return false;
        }
        boolean notExpire = Long.parseLong((String) m.get("lastinipdate")) > 0 && (Long.parseLong((String) m.get("lastinipdate")) + 30 * 24 * 60 * 60 * 1000L) > System.currentTimeMillis();
        return notExpire;
    }

    /**
     * logindate 必须在30天内登录一次--放置呗用户手动修改掉了cookie过期时间.
     */
    private boolean checkLoginDate(Map<String, Object> m) {
        if (!m.containsKey("logindate")) {
            return false;
        }
        boolean notExpire = Long.parseLong((String) m.get("logindate")) == 0 || (Long.parseLong((String) m.get("logindate")) + 30 * 24 * 60 * 60 * 1000L) > System.currentTimeMillis();
        return notExpire;
    }

}
